package com.imagination.applet.domain.revenue.charge.service.imlp;

import com.google.common.collect.Maps;
import com.imagination.applet.controller.api.response.OrderPrepayResponse;
import com.imagination.applet.controller.web.configuration.UserHolder;
import com.imagination.applet.domain.revenue.charge.model.StarCharge;
import com.imagination.applet.domain.revenue.charge.service.StarChargeService;
import com.imagination.applet.domain.revenue.order.model.OrderType;
import com.imagination.applet.domain.revenue.order.model.UserOrder;
import com.imagination.applet.domain.revenue.order.service.OrderService;
import com.imagination.applet.domain.support.payment.service.PayService;
import com.imagination.applet.domain.user.model.User;
import com.imagination.applet.domain.user.service.UserService;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class StarChargeServiceImpl implements StarChargeService {

    private final OrderService orderService;
    private final UserService userService;
    private final PayService payService;

    @Override
    public PrepayWithRequestPaymentResponse submit(String level) {
        Long userId = UserHolder.getUserId();
        StarCharge starCharge = StarCharge.valueOf(level);
        UserOrder order = orderService.createOrder(userId, OrderType.STAR_CHARGE,
                starCharge.getPrice(), starCharge.getCurrency(),
                buildExtension(starCharge));
        Optional<User> user = userService.getByUserId(order.getUserId());
        return payService.prePay2(user.get().getOpenId(), order.getTraceNo(),
                order.getAmount(), order.getCurrency(),
                order.getOrderType().getDescription());
    }

    private Map<String, Object> buildExtension(StarCharge starCharge) {
        Map<String, Object> extension = Maps.newHashMap();
        extension.put("charge_level", starCharge.getLevel());
        extension.put("starNumber", starCharge.getStarNumber());
        return extension;
    }
}
